package com.unitedats.HR.Servlet;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.unitedats.HR.Entity.HrDepartment;
import com.unitedats.common.Servlet.BasicServlet;
import com.unitedats.common.bo.Message;
import com.unitedats.common.util.Common;
import com.unitedats.common.util.DateUtil;
import com.unitedats.common.util.WebUtil;

public class DepartmentAddProcessServlet extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		int parentId = 0;
		int level = 0;
		String path = null;

		String[] parentIds = WebUtil.getParamValues(request, "parent");
		/*
		 * for (int i = depList.length - 1; i >= 0; i--) { if
		 * (!depList[i].equals("")) { parentId = Integer.parseInt(depList[i]);
		 * level = i + 1; break; } }
		 */
		String parentIdStr = parentIds[parentIds.length - 1];
		if ("".equals(parentIdStr)) {
			parentIdStr = parentIds[parentIds.length - 2];
			level = parentIds.length;
			path = Common.concatenateValues(Arrays.copyOfRange(parentIds, 0, parentIds.length - 1));
		} else {
			parentIdStr = parentIds[parentIds.length - 1];
			level = parentIds.length + 1;
			path = Common.concatenateValues(parentIds);
		}
		parentId = Integer.parseInt(parentIdStr);

		HrDepartment dep = new HrDepartment();

		dep.setParentId(dbm.findById(parentId, HrDepartment.class));
		dep.setName(WebUtil.getParamValue(request, "name", ""));
		// dep.setDescription(WebUtil.getParamValue(request, "description",""));
		dep.setLevel(level);
		dep.setPath(path);
		dep.setStatus(true);
		dep.setCreatedIn(DateUtil.getCurrentDate());
		dep.setCreatedBy(getSessionUser(request).getEmpId());

		dbm.mergeEntity(dep);

		setMessage(request, new Message("New department has been added successfuly", Message.MESSAGE_TYPE.SUCCESS));
		sendRedirect(request, response, "DepartmentAddDisplay");
	}
}
